import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const channelStore = createSlice({
	name: 'channel',

	// 初始化状态
	initialState: {
		channelList: [],
	},

	// 定义reducers [同步方法]
	reducers: {
		setChannels(state, action) {
			state.channelList = action.payload
		},
	},
})

// 解构 actionCreater 函数
const { setChannels } = channelStore.actions
// 获取 reducer
const channelReducer = channelStore.reducer

// 异步请求函数 [异步方法]
const fetchChannelList = () => {
	return async (dispatch) => {
		const res = await axios.get('http://geek.itheima.net/v1_0/channels')
		dispatch(setChannels(res.data.data.channels))
	}
}

// 导出 actionCreater
export { fetchChannelList }
// 默认导出 reducer
export default channelReducer
